package com.ayf.payment.game.api.service.platform;

import com.alibaba.fastjson.JSON;
import com.ayf.payment.game.api.dto.platform.TokenAdmin;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 *
 *
 * @author wwl
 * @date 2020/3/4 15:16
 */
@Component
public class TokenAdminRepository {
    public static final long ACCESS_TOKEN_ADMIN_EXPIRED_SECOND = 60L * 60 * 24 * 7;

    public static final long REFRESH_TOKEN_ADMIN_EXPIRED_SECOND = 60L * 60 * 24 * 14;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public boolean save(TokenAdmin entity) {
        try {
            redisTemplate.boundValueOps(genAccessTokenKey(entity.getAccessToken()))
                    .set(entity.getRefreshToken(), ACCESS_TOKEN_ADMIN_EXPIRED_SECOND, TimeUnit.SECONDS);

            redisTemplate.boundValueOps(genAdminUserIdAndAppIdKey(entity.getAdminUserId()))
                    .set(entity.getAccessToken(), ACCESS_TOKEN_ADMIN_EXPIRED_SECOND, TimeUnit.SECONDS);

            redisTemplate.boundValueOps(genRefreshToken(entity.getRefreshToken()))
                    .set(JSON.toJSONString(entity), REFRESH_TOKEN_ADMIN_EXPIRED_SECOND, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            LogPortal.error("保存token失败，发生{}异常, token信息[{}]",e,e.getClass().getName(),entity.toString());
            return false;
        }
    }

    public void delete(String accessToken) {
        if (StringUtils.isBlank(accessToken)) {
            return;
        }
        String refreshToken = redisTemplate.boundValueOps(genAccessTokenKey(accessToken)).get();
        deleteRefreshToken(refreshToken);
    }

    public void deleteRefreshToken(String refreshToken) {
        if (StringUtils.isBlank(refreshToken)) {
            return;
        }
        TokenAdmin entity = getTokenByRefreshToken(refreshToken);
        if (entity == null) {
            return;
        }
        List<String> list = new ArrayList<String>(3);
        list.add(genAccessTokenKey(entity.getAccessToken()));
        list.add(genAdminUserIdAndAppIdKey(entity.getAdminUserId()));
        list.add(genRefreshToken(entity.getRefreshToken()));
        redisTemplate.delete(list);
    }

    public void delete(Integer adminUserId) {
        String key = genAdminUserIdAndAppIdKey(adminUserId);
        String accessToken = redisTemplate.boundValueOps(key).get();
        delete(accessToken);
    }

    public TokenAdmin getTokenByAccessToken(String accessToken) {
        if (StringUtils.isBlank(accessToken)) {
            return null;
        }
        try {
            String refreshToken = redisTemplate.boundValueOps(genAccessTokenKey(accessToken)).get();
            return getTokenByRefreshToken(refreshToken);
        } catch (Exception e) {
            LogPortal.error("获取TokenAdmin失败，发生{}异常, accessToken[{}]",e,e.getClass().getName(),accessToken);
            return null;
        }
    }

    public TokenAdmin getTokenByRefreshToken(String refreshToken) {
        if (StringUtils.isBlank(refreshToken)) {
            return null;
        }
        String json = redisTemplate.boundValueOps(genRefreshToken(refreshToken)).get();
        if (StringUtils.isBlank(json)) {
            return null;
        }
        return JSON.parseObject(json, TokenAdmin.class);
    }

    private static String genAdminUserIdAndAppIdKey(Integer adminUserId) {
        return "token-admin-userid-".concat(String.valueOf(adminUserId));
    }

    private static String genAccessTokenKey(String accessToken) {
        return "token-admin-accesstoken-".concat(accessToken);
    }

    private static String genRefreshToken(String refreshToken) {
        return "token-admin-accesstoken-".concat(refreshToken);
    }
}
